package cn.edu.nwafu.hjpg.controller;

import cn.edu.nwafu.hjpg.common.HttpResult;

import cn.edu.nwafu.hjpg.entity.Evaluate;
import cn.edu.nwafu.hjpg.entity.Prove;
import cn.edu.nwafu.hjpg.service.*;
import cn.edu.nwafu.hjpg.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/evaluate")

public class EvaluateController {
    final ElementService elementService;
    final EvaluateService evaluateService;
    final WaterpfxsService waterpfxsService;
    final ProveService proveService;

    public EvaluateController(ElementService elementService, EvaluateService evaluateService, WaterpfxsService waterpfxsService, ProveService proveService) {
        this.elementService = elementService;
        this.evaluateService = evaluateService;
        this.waterpfxsService = waterpfxsService;
        this.proveService = proveService;
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addEvaluate(@RequestBody Evaluate evaluate) {
        System.out.println("evaluate:" + evaluate.getFaWzlb());
        //当前登录用户名
        if(evaluateService.findAllByCasNo(evaluate.getCasNo())!=null){
            return HttpResult.ok("fail");
        }
        else {
            String userName = SecurityUtils.getUsername();
            evaluate.setUserName(userName);
            Date date = new Date();
            String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
            System.out.println("data:" + dateStr);
            evaluate.setDate(dateStr);
            return HttpResult.ok(evaluateService.addEvaluate(evaluate));
        }
    }

    @RequestMapping(value = "/evaluate", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getEvaluate(@RequestParam() String casNo) {
        System.out.println("casNo:" + casNo);
        //当前登录用户名
        if(evaluateService.findAllByCasNo(casNo)!=null){
            return HttpResult.ok("fail");
        }
        else {
            return HttpResult.ok("success");
        }
    }

    @GetMapping("/getEvaluateData")
    @ResponseBody
    public HttpResult getEvaluateData() {
        return HttpResult.ok(evaluateService.findAll());
    }


    @RequestMapping(value = "/waterpfxs", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult findWaterpfxsByWaterParams(@RequestParam() String wzlb, @RequestParam() String process, @RequestParam() String fiberId){
        return HttpResult.ok(waterpfxsService.findWaterpfxsByWzlbAndProcessAndFiberId(wzlb,process,fiberId));
    };

    @RequestMapping(value = "/findbycasno",method = RequestMethod.POST)
    @ResponseBody
    public HttpResult findAllByCasNo(@RequestParam() String casNo){
        return HttpResult.ok(evaluateService.findAllByCasNo(casNo));
    }

    @Value("${pdf.path}")
    private String path;
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public HttpResult upload(MultipartFile file,String cas) {
        String fileName = file.getOriginalFilename();
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = cas +"_"+fileName;
        try {
            file.transferTo(new File(path+fileName));
//            questionnaire.setCreateTime(new Date());
//            questionnaire.setPdfPath(path+fileName);
//            questionnaireService.addQuestionnaire(questionnaire);

        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.error("上传失败");
        }

        Prove prove = new Prove();
        prove.setCasNo(cas);
        prove.setFileName(file.getOriginalFilename());
        prove.setFilePath(path+fileName);
        proveService.addProve(prove);
        return HttpResult.ok("上传成功");
    }
    @RequestMapping(value = "/findProveByCas",method = RequestMethod.GET)
    @ResponseBody
    public HttpResult findProveByCas(@RequestParam() String casNo){
        return HttpResult.ok(proveService.findByCas(casNo));
    }

    @RequestMapping(value = "downloadProve" ,method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadProve(String cas,String filename) throws IOException {
        // 读取pdf文件到字节里
            Prove prove = proveService.findByCasFilename(cas,filename);
            if(prove!=null){
                Path path = Paths.get(prove.getFilePath());
                byte[] contents = Files.readAllBytes(path);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/pdf"));
                filename = UUID.randomUUID().toString();
                headers.add("content-disposition", "inline;filename=" + filename);
                headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
                ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
                return response;
            }
           return null;
    }
    @RequestMapping(value = "/findPDFByCas",method = RequestMethod.GET)
    @ResponseBody
    public HttpResult findPDFByCas(@RequestParam() String casNo,@RequestParam() String fileName){
        return HttpResult.ok(proveService.findByCasFilename(casNo,fileName));
    }
}
